package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.text.DecimalFormat;
/**
 * 
 * @author msjykf
 * 生成对账单数据文件
 * {"batch_id":"","startdate":"","enddate":"","filepath":"","filename":""}
 *
 */
public class BillDataProcess implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(BillDataProcess.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
		def jsonbody = Util.getRequestBody(request,'utf-8'); //获取报文
		//log.debug("jsonbody:"+jsonbody);
		if(jsonbody.equals("")) {
			return "{\"msg\": \"未获取到入参报文！\",\"code\": -2}"
		}
		JSONObject obj = JSONObject.fromObject(jsonbody);
		def batch_id = Util.filterForObject(obj.get("batch_id")); //批次号
		def firstDay = Util.filterForObject(obj.get("startdate")); //对账单开始日期
		def lastDay = Util.filterForObject(obj.get("enddate")); //对账单截止日期
		def relativepath = Util.filterForObject(obj.get("filepath")); //文件存储相对路径
		def filename = Util.filterForObject(obj.get("filename")); //文件名称
		if(batch_id.equals("")){
			return "{\"msg\": \"批次号不能为空！\",\"code\": -2}"
		}else if(firstDay.equals("")){
			return "{\"msg\": \"对账单开始日期！\",\"code\": -2}"
		}else if(lastDay.equals("")){
			return "{\"msg\": \"对账单截止日期！\",\"code\": -2}"
		}else if(relativepath.equals("")){
			return "{\"msg\": \"文件存储路径！\",\"code\": -2}"
		}
		PropertiesUtil properties = new PropertiesUtil();
		def fileStore = properties.readValue("fileStore"); //文件存储根目录
		try {
			def currentdate = Util.getNowString("yyyyMMdd");
			File file = new File(fileStore+relativepath); //文件存储绝对路径
			//文件不存在，则创建文件
			if(!file.exists()) {
				file.createNewFile();
			}
			DecimalFormat tf = new DecimalFormat("0.00");
			DecimalFormat ff = new DecimalFormat("0.0000");
			FileWriter fw = new FileWriter(file,true); //设置成true就是追加
			BufferedWriter bw=new BufferedWriter(fw);
			JSONObject jsonout = new JSONObject();
			JSONObject jsonin = new JSONObject();
			JSONArray arr = new JSONArray();
			def smap = eliteBean.chaxun_sql("select max(case when date_i<"+firstDay+" then date_i else null end) as req_start,max(case when date_i<"+lastDay+" then date_i else null end) as req_end from c_calendar where workflag=1","dataSource");
			def req_start = smap[0].get("req_start");
			def req_end = smap[0].get("req_end");
			def sk_invpty = ""; //客户编号
			def bk_fundaccount = ""; //基金账号
			def content = "";
			def num = 0;
			def succnum = 0;
			def failnum = 0;
			def i = 0;
			def list = eliteBean.chaxun_sqlRowSet("select sk_invpty,invpty_name,address,zipcode,bk_fundaccount,agencyname,open_date from statement_custinfo where batch_id='"+batch_id+"'","dataSource");
			while(list.next()){
				num++;
				try {
					bk_fundaccount = Util.filterForObject(list.getString(5)).split(",")[0];
					sk_invpty = Util.filterForObject(list.getInt(1));
					jsonout.put("c1","1"); //标识 客户信息默认为1
					jsonout.put("c2",currentdate+bk_fundaccount); //ID
					jsonout.put("c3",""); //客户标志 1：标志新客户  0：表示老客户
					jsonout.put("c4",Util.filterForObject(list.getString(2))); //收件人名称
					jsonout.put("c5",Util.filterForObject(list.getString(3))); //地址
					jsonout.put("c6",Util.filterForObject(list.getString(4))); //邮编
					jsonout.put("c7",Util.filterForObject(list.getString(2))); //客户名称
					jsonout.put("c8",""); //客户类型
					jsonout.put("c9",sk_invpty); //客户号
					jsonout.put("c10",bk_fundaccount); //基金账号
					jsonout.put("c11",Util.filterForObject(list.getString(6))); //开户机构
					jsonout.put("c12",""); //交易账号
					jsonout.put("c13",""); //证件类型
					jsonout.put("c14",""); //证件号码
					jsonout.put("c15",""); //联系电话
					jsonout.put("c16",""); //手机
					jsonout.put("c17",""); //Email地址
					jsonout.put("c18",""); //账户默认分红方式
					jsonout.put("c19","寄送"); //对账单寄送方式
					jsonout.put("c20",""); //经办人姓名
					jsonout.put("c21",""); //经办人证件号码
					jsonout.put("c22",""); //开户银行
					jsonout.put("c23",""); //开户户名
					jsonout.put("c24",""); //银行账号
					jsonout.put("c25",""); //备注
					jsonout.put("c26",""); //特殊代码
					jsonout.put("c27",Util.filterForObject(list.getString(7))); //开户日期
					jsonout.put("c28",""); //资料最后修改日期
					jsonout.put("c29",""); //客户传真
					jsonout.put("c30",firstDay); //账单确认起始日期
					jsonout.put("c31",lastDay); //账单确认截止日期
					jsonout.put("c32",req_start); //账单申请起始日期
					jsonout.put("c33",req_end); //账单申请截止日期
					jsonout.put("c34","交易对账单"); //对账单标题
					jsonout.put("c35",req_end-1); //T日净值截止日
					jsonout.put("c36",req_end); //T+1日净值截止日
					jsonout.put("c37",""); //账户状态
					jsonout.put("c38","按季"); //寄送频率
					jsonout.put("c39",""); //客户的等级
					jsonout.put("c40",""); //专户标志
					jsonout.put("c41",""); //性别
					jsonout.put("c42",Util.filterForObject(list.getString(5))); //多基金账号
					smap = eliteBean.chaxun_sql("select bk_product,product_cname,agencyname,bonustype,income,shares,netvalue,capital from statement_productinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+" order by bk_product","dataSource");
					/**基金余额信息*/
					for(i=0;i<smap.size();i++) {
						jsonin.put("c1","2"); //标识  份额余额信息默认为2
						jsonin.put("c2",Util.filterForObject(smap[i].get("bk_product"))); //基金代码
						jsonin.put("c3",Util.filterForObject(smap[i].get("product_cname"))); //基金名称
						jsonin.put("c4",""); //收费方式
						jsonin.put("c5",Util.filterForObject(smap[i].get("bonustype"))); //分红方式
						jsonin.put("c6",tf.format(smap[i].get("shares",0))); //基金余额
						jsonin.put("c7",""); //冻结份额
						jsonin.put("c8",tf.format(smap[i].get("shares",0))); //可用份额
						jsonin.put("c9",0); //T日单位净值
						jsonin.put("c10",ff.format(smap[i].get("netvalue",0))); //T+1日单位净值
						jsonin.put("c11",0); //T日市值
						jsonin.put("c12",tf.format(smap[i].get("capital",0))); //T+1日市值
						jsonin.put("c13",Util.filterForObject(smap[i].get("agencyname"))); //销售商
						jsonin.put("c14",""); //托管网点
						jsonin.put("c15",""); //基金性质
						jsonin.put("c16",""); //总成本
						jsonin.put("c17",tf.format(smap[i].get("income",0))); //T日未结转收益
						jsonin.put("c18",""); //T+1日未结转收益
						jsonin.put("c19",req_end-1); //T日净值截止日
						jsonin.put("c20",req_end); //T+1日净值截止日
						jsonin.put("c21",""); //浮动盈亏
						jsonin.put("c22",""); //投资收益
						jsonin.put("c23",Util.filterForObject(smap[i].get("bk_product"))); //外部基金代码
						jsonin.put("c24",Util.filterForObject(smap[i].get("product_cname"))); //外部基金名称
						jsonin.put("c25",bk_fundaccount); //基金账号
						arr.add(jsonin);
					}
					jsonout.put("tablea",arr);
					jsonin = new JSONObject();
					arr = new JSONArray();
					smap = eliteBean.chaxun_sql("select req_date,confirm_date,bk_product,product_cname,agencyname,tradetype,amount,shares,netvalue,tradefare from statement_tradeinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+" order by req_date","dataSource");
					/**基金交易信息*/
					for(i=0;i<smap.size();i++) {
						jsonin.put("c1","3"); //标识  基金交易信息默认为3
						jsonin.put("c2",Util.filterForObject(smap[i].get("req_date"))); //申请日期
						jsonin.put("c3",""); //申请编号
						jsonin.put("c4",""); //交易账号
						jsonin.put("c5",""); //申请金额
						jsonin.put("c6",""); //申请份额
						jsonin.put("c7",Util.filterForObject(smap[i].get("confirm_date"))); //确认日期
						jsonin.put("c8",""); //确认编号
						jsonin.put("c9",Util.filterForObject(smap[i].get("tradetype"))); //交易名称
						jsonin.put("c10",Util.filterForObject(smap[i].get("bk_product"))); //基金代码
						jsonin.put("c11",Util.filterForObject(smap[i].get("product_cname"))); //基金名称
						jsonin.put("c12",""); //收费方式
						jsonin.put("c13",tf.format(smap[i].get("amount",0))); //确认金额
						jsonin.put("c14",tf.format(smap[i].get("shares",0))); //确认份额
						jsonin.put("c15",tf.format(smap[i].get("tradefare",0))); //交易费
						jsonin.put("c16",ff.format(smap[i].get("netvalue",0))); //单位净值
						jsonin.put("c17",Util.filterForObject(smap[i].get("agencyname"))); //销售商
						jsonin.put("c18",""); //托管网点
						jsonin.put("c19",""); //托管网点的余额
						jsonin.put("c20",""); //备注
						jsonin.put("c21",""); //失败原因
						jsonin.put("c22",""); //每单位分红
						jsonin.put("c23",""); //利息转份额
						jsonin.put("c24",""); //总费用
						jsonin.put("c25",Util.filterForObject(smap[i].get("bk_product"))); //外部基金代码
						jsonin.put("c26",Util.filterForObject(smap[i].get("product_cname"))); //外部基金名称
						jsonin.put("c27",bk_fundaccount); //基金账号
						arr.add(jsonin);
					}
					jsonout.put("tableb",arr);
					jsonin = new JSONObject();
					arr = new JSONArray();
					content = Util.getMergeContent(JSONObject.fromObject(jsonout).toString(),""+filename+"","utf-8");
					bw.write(content);
					bw.newLine();
					if(num==500) {
						num = 0;
						bw.flush();
					}
					String[] data=new String[6];
					data[0] = "insert into statement_custinfo_his(sk_invpty,batch_id,invpty_name,address,zipcode,bk_fundaccount,createdate,agencyname,open_date) select sk_invpty,batch_id,invpty_name,address,zipcode,bk_fundaccount,createdate,agencyname,open_date from statement_custinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+"";
					data[1] = "delete from statement_custinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+"";
					data[2] = "insert into statement_productinfo_his(batch_id,sk_invpty,product_cname,agencyname,bonustype,income,shares,netvalue,capital,createdate,bk_product) select batch_id,sk_invpty,product_cname,agencyname,bonustype,income,shares,netvalue,capital,createdate,bk_product from statement_productinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+"";
					data[3] = "delete from statement_productinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+"";
					data[4] = "insert into statement_tradeinfo_his(batch_id,sk_invpty,req_date,confirm_date,bk_product,tradetype,amount,shares,netvalue,tradefare,createdate,product_cname,agencyname) select batch_id,sk_invpty,req_date,confirm_date,bk_product,tradetype,amount,shares,netvalue,tradefare,createdate,product_cname,agencyname from statement_tradeinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+"";
					data[5] = "delete from statement_tradeinfo where batch_id='"+batch_id+"' and sk_invpty="+sk_invpty+"";
					int[] dataresult = eliteBean.updateBatch(data,"dataSource");
					succnum++;
 				}catch(Exception e) {
					 failnum++;
					log.error("ErrorMessage： ",e);
					}			
			}
			bw.flush();
			bw.close();
			fw.close();
			eliteBean.update("update statement_batch set acceptstate=3,writesucc=writesucc+"+succnum+",writefailed="+failnum+" where batch_id='"+batch_id+"'","dataSource");
			return "{\"msg\": \"请求接口成功！\",\"code\": 1}"
		}catch(Exception e) {
				log.error("ErrorMessage： ",e);
				return "{\"msg\": \"请求接口失败！\",\"code\": -1}"
			}
	}
}	